package com.gin.kotlin.no_gay_alliance.model

import com.gin.kotlin.no_gay_alliance.database.entity.IpLocationHistory
import java.time.ZonedDateTime

/**
 * ip属地，时间范围
 * @property location String
 * @property start ZonedDateTime
 * @property end ZonedDateTime
 * @constructor
 */
data class IpLocationRange(
    val location: String,
    val start: ZonedDateTime,
    var end: ZonedDateTime = start,
) {
    companion object {
        /**
         * 将IP属地历史转换为时间范围格式
         * @param histories List<IpLocationHistory>
         * @return List<IpLocationRange>
         */
        fun merge(histories: List<IpLocationHistory>): List<IpLocationRange> {
            val list = mutableListOf<IpLocationRange>()

            histories.forEach { hi ->
                val last = list.lastOrNull()

                // 如果存在最后一项，且属地一致则修改结束时间 ; 否则创建一个新的
                if (last?.location == hi.location)
                    last.end = hi.timestamp
                else
                    list.add(IpLocationRange(hi.location, hi.timestamp))
            }
            return list
        }
    }
}
